package com.qinghong.elasticsearchjd.utils;

import com.qinghong.elasticsearchjd.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Component
public class HtmlParseUtil {
    public static void main(String[] args) throws IOException {
        new HtmlParseUtil().parseJD("vue").forEach(System.out::println);
    }

    public List<Content> parseJD(String keywords) throws IOException {
        // 获取请求
        String url = "https://search.jd.com/Search?keyword="+keywords;
        // 解析网页 js的
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
//        System.out.println(element);
        // 获取所有li
        Elements elements = element.getElementsByTag("li");

        List<Content> goodList = new ArrayList<>();
        // 获取元素内容
        for (Element element1 : elements) {
            // 图片延迟加载
            // source-data-lazy-img
            String img = element1.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = element1.getElementsByClass("p-price").eq(0).text();
            String title = element1.getElementsByClass("p-name").eq(0).text();
            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setTitle(title);
            goodList.add(content);
            System.out.println(img);
            System.out.println(price);
            System.out.println(title);
        }
        return goodList;
    }
}
